package com.leen.security.filter;

import com.alibaba.fastjson.JSONObject;

import com.leen.common.vo.ResultEnum;
import com.leen.common.vo.ResultVO;
import com.leen.security.ServletUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * spring security认证失败(exception)
 *
 * @author admin
 * @date 2021-05-13
 */
@Component
@Log4j2
public class UnauthorizedHandler implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

        log.debug("请求访问：{}，认证失败，无法访问系统资源", request.getRequestURI());

        String msg =  "请求访问："+request.getRequestURI()+"，认证失败，无法访问系统资源";

        ResultVO<String> resultVO=ResultVO.failed(ResultEnum.Forbidden);
        resultVO.setMessage(msg);
        ServletUtil.renderString(response, JSONObject.toJSONString(resultVO));

    }
}
